/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useRef, useState, useMemo, useEffect } from 'react';
import { connect, useSelector } from 'umi';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import ProDescriptions from '@ant-design/pro-descriptions';
import { getNoticeList } from '@/services/inn';
import { Button, Input, Drawer, Spin, Space } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ConnectState } from '@/models/connect';
import type { Dispatch } from 'umi';
import type { TableListItem } from '../types/NoticeVerify';

interface NoticePageTypes {
  type: string;
  submitLoading: boolean | undefined;
  dispatch: Dispatch;
  noticeDetailLoading: boolean | undefined;
  activeKey: string;
}

const NoticePage: React.FC<NoticePageTypes> = ({
  type,
  submitLoading = false,
  dispatch,
  noticeDetailLoading,
  activeKey,
}) => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>(); // form表单实例
  const [visible, setVisible] = useState<boolean>(false);
  const [record, setRecord] = useState<TableListItem>({});
  const [showButton, setShowButton] = useState<boolean>(false);
  const [noContent, setNoContent] = useState<boolean>(false);

  const getNoticeDetail = useCallback(
    (id: TableListItem['last_id'], get_next?: boolean) => {
      dispatch({
        type: 'noticeVerify/getNoticeDetail',
        payload: {
          id,
          get_next: get_next ? 1 : undefined,
        },
      })
        .then((res: { data: TableListItem }) => {
          const { data } = res;
          if (type === 'todo') {
            setShowButton(true);
          }
          setRecord(data);
          setNoContent(false);
        })
        .catch(() => {
          setNoContent(true);
        });
    },
    [dispatch, type],
  );

  const onEdit = useCallback(
    (open, id) => {
      setVisible(open);
      getNoticeDetail(id, true);
    },
    [getNoticeDetail],
  );

  const columns: ProColumns<TableListItem>[] = useMemo(
    () => [
      {
        title: '注册手机号',
        dataIndex: 'phone',
        search: false,
      },
      {
        title: '加盟商',
        dataIndex: 'league_name',
        search: false,
      },
      {
        title: '标题',
        dataIndex: 'title',
        ellipsis: true,
        search: false,
      },
      {
        title: '状态',
        dataIndex: 'status',
        search: false,
        render: (rext) => {
          switch (rext) {
            case '2':
              return '待审核';
            case '3':
              return '已同意';
            case '4':
              return '已拒绝';
            default:
              return '-';
          }
        },
      },
      {
        title: '创建时间',
        dataIndex: 'created_time',
        search: false,
      },
      {
        title: '通过时间',
        dataIndex: 'update_time',
        search: false,
        hideInTable: type !== 'agreed',
      },
      {
        title: '拒绝时间',
        dataIndex: 'update_time',
        search: false,
        hideInTable: type !== 'refused',
      },
      {
        title: '操作',
        valueType: 'option',
        dataIndex: 'option',
        fixed: 'right',
        width: 50,
        render: (_, data) => <a onClick={() => onEdit(true, data.id)}>详情</a>,
      },
      {
        hideInTable: true,
        dataIndex: 'phone',
        renderFormItem: () => {
          return <Input placeholder='请输入加盟商手机号查询' />;
        },
      },
    ],
    [type, onEdit],
  );

  useEffect(() => {
    if (type === 'todo') {
      setShowButton(true);
    }
    if (type === activeKey) {
      actionRef.current?.reload(false);
      const triggerReset = actionRef.current?.reset;
      if (triggerReset) {
        triggerReset();
      }
    }
  }, [type, activeKey]);

  const handleRequest = useCallback(
    (params) => {
      const { current: page, pageSize, ...rest } = params;
      switch (type) {
        case 'agreed':
          return getNoticeList({ ...rest, page, pageSize, status: 3 });
        case 'refused':
          return getNoticeList({ ...rest, page, pageSize, status: 4 });
        default:
          return getNoticeList({ ...rest, page, pageSize, status: 2 });
      }
    },
    [type],
  );

  const onSubmit = useCallback(
    (agree: boolean) => {
      dispatch({
        type: 'noticeVerify/releaseNotice',
        payload: {
          status: agree ? 3 : 4,
          id: record.id,
        },
      }).then(() => {
        setShowButton(false);
        actionRef.current?.reload(false);
      });
    },
    [dispatch, record],
  );

  const onClose = useCallback(() => {
    setVisible(false);
  }, []);

  const afterVisibleChange = useCallback(
    (open: boolean) => {
      if (type === 'todo' && open) {
        setShowButton(true);
      }
    },
    [type],
  );

  return (
    <>
      <DragTable>
        <ProTable<TableListItem>
          actionRef={actionRef}
          rowKey='id'
          request={handleRequest}
          columns={columns}
          className='kb-pro-table'
          pagination={{
            pageSize: 30,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          options={false}
          search={{
            className: 'kb-pro-table-form',
            labelWidth: 'auto',
            collapseRender: () => false,
            optionRender: (_, { form }) => [
              <Button
                key='phone'
                type='primary'
                onClick={() => {
                  form?.submit();
                }}
              >
                搜索
              </Button>,
            ],
          }}
          scroll={{ x: 640 }}
        />
      </DragTable>

      <Drawer
        visible={visible}
        width={winSize === 'xs' ? 300 : 700}
        closable={false}
        onClose={onClose}
        title={record.title}
        afterVisibleChange={afterVisibleChange}
      >
        <Spin spinning={submitLoading}>
          <ProDescriptions>
            <ProDescriptions.Item>
              <div dangerouslySetInnerHTML={{ __html: record.content || '' }} />
            </ProDescriptions.Item>
            {noContent && <ProDescriptions.Item>暂无通知内容！</ProDescriptions.Item>}
          </ProDescriptions>
        </Spin>
        {showButton && (
          <div style={{ height: 32 }}>
            <Space
              size='large'
              style={{
                position: 'absolute',
                width: '100%',
                left: 0,
                bottom: 80,
                justifyContent: 'center',
              }}
            >
              <Button
                type='primary'
                key='agree'
                disabled={submitLoading || noContent}
                onClick={() => onSubmit(true)}
              >
                同意发布
              </Button>
              <Button
                danger
                key='refuse'
                disabled={submitLoading || noContent}
                onClick={() => onSubmit(false)}
              >
                拒绝发布
              </Button>
            </Space>
          </div>
        )}
        <div style={{ height: 50 }}>
          <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button
              type='ghost'
              style={{ marginRight: 8 }}
              disabled={submitLoading || record.last_id === ''}
              loading={noticeDetailLoading}
              onClick={() => getNoticeDetail(record.last_id, true)}
            >
              查看上一条
            </Button>
            <Button
              type='primary'
              disabled={submitLoading || record.front_id === ''}
              loading={noticeDetailLoading}
              onClick={() => getNoticeDetail(record.front_id, true)}
            >
              查看下一条
            </Button>
          </div>
        </div>
      </Drawer>
    </>
  );
};

export default connect(({ loading }: ConnectState) => ({
  submitLoading: loading.effects['noticeVerify/releaseNotice'],
  noticeDetailLoading: loading.effects['noticeVerify/getNoticeDetail'],
}))(React.memo(NoticePage));
